<template>
	<view class="observe-content">
		<view class="observe-top">
			<rf-navbar title="孩子共管" @click="onBack"></rf-navbar>
		</view>

		<view class="observe-bottom" v-if="data.length>0">
			<u-index-list :scrollTop="scrollTop" :index-list="data.map(item => item.code)" customNavHeight="97"
				bottom="90">
				<u-checkbox-group v-model="checkboxValue1" placement="column" :iconSize="21">
					<template v-for="(item, index) in data">

						<!-- #ifdef APP-NVUE -->
						<u-index-anchor :text="data.map(item => item.code)[index]" :index="item.code" bgColor="#F5F6FA"
							height="20"></u-index-anchor>
						<!-- #endif -->

						<u-index-item>
							<!-- #ifndef APP-NVUE -->
							<u-index-anchor :text="data.map(item => item.code)[index]" :index="item.code"
								bgColor="#F5F6FA" height="20"></u-index-anchor>
							<!-- #endif -->
							<view class="list-cell" v-for="(cell, row) in item.list" @click="childDetails(cell)">
								<u-checkbox :checked="cell.isSel" :key="cell.childId" :name="cell.childId"
									activeColor="#58C866" @change="handleChange(cell)"></u-checkbox>
								<view class="cell-image">
									<rf-avatar :avatarUrl="cell.headSculpture" :gender="cell.childSex"></rf-avatar>
								</view>
								<view class="cell-text">
									<view class="cell-text-top">
										<text>{{ cell.childName }}</text>
										<image class="icon-my" style="width: 35rpx;height: 35rpx; margin-left: 20rpx;"
											@click.stop="shareChild(cell)"
											v-if="cell.shareList && cell.shareList.length>0">
										</image>
									</view>
									<view class="cell-text-bom">{{getChildAge(cell)}}</view>
								</view>
								<view class="right" style="flex: 1; display: flex;justify-content: flex-end;"
									v-if="authRelease(cell)">
									<view
										style="width: 88rpx;height: 44rpx; display: flex;justify-content: center;align-items: center;"
										@click="OnClickedReleaseChild(cell)">
										<text style="color: #2DAE3D; font-size: 26rpx; display: block;">解除</text>
									</view>
								</view>
							</view>
						</u-index-item>
					</template>
				</u-checkbox-group>
			</u-index-list>
		</view>
		<!-- 数据为空页面 -->
		<view class="observe-bottom" v-else>
			<view
				style="background-color: #fff; width: 100%; height: 400px; display: flex; justify-content: center; align-items: center;">
				<u-empty mode="car" :marginTop="50" text="暂无数据" icon="/static/images/common/empty.png"></u-empty>
			</view>
		</view>
		<!-- 页脚 -->
		<view class="footer">
			<view class="container">
				<u-checkbox-group placement="column" :iconSize="21">
					<u-checkbox activeColor="#58C866" :checked="isallcheck" @change="checkboxChange"
						label="全选"></u-checkbox>
				</u-checkbox-group>
				<button class="btn tColor" @click="onClickedRelease" :class="{disabled:isReleaseButtonDisable}"
					:disabled="isReleaseButtonDisable">解除共管</button>
				<view class="btn bg" @click="onClickedJoint">进行共管</view>
			</view>
		</view>

		<rf-alertJoint :show="showChildJoint" :childs="selChild" v-model="shareId" @close="showChildJoint=false"
			@confirm="OnClickedchildJoin"></rf-alertJoint>
		<rf-toast :show="showJoinSuc" :isSus="true" title="共管成功" :des="showName" @click="showJoinSuc=false"></rf-toast>
		<rf-toast :show="showJoinFail" :isSus="false" title="共管失败" des="添加失败,请检查您输入的共管人的ID是否有误."
			@click="showJoinFail=false"></rf-toast>
		<rf-toast :show="showRelieveFail" :isSus="false" title="提示" des="解除共管操作,仅支持对单个孩子进行."
			@click="showRelieveFail=false"></rf-toast>

		<rf-toast :show="showRelieveFail1" :isSus="false" title="提示" des="请选择要解除共管关系的孩子"
			@click="showRelieveFail1=false"></rf-toast>
		<!-- 解除共管关系提示 -->
		<rf-toast :show="showRelieveFail2" :isSus="false" title="提示" des="请联系共管创建人,解除孩子共管关系."
			@click="showRelieveFail2=false"></rf-toast>

		<rf-toast :show="showRelieveFail3" :isSus="false" title="提示" des="请确认孩子存在共管关系."
			@click="showRelieveFail3=false"></rf-toast>

		<rf-toast :show="showRelieve" :isSus="isSuc" :title="title" :des="des" @click="showRelieve=false"></rf-toast>

		<!-- 显示共管信息 -->
		<rf-shareChild :show="shareChildShow" :child="childInfo" @confirm="shareChildShow=false"
			@set="shareChildShow=false"></rf-shareChild>
		<!-- 解除共管 -->
		<rf-releaseChild :show="releaseChildShow" :child="childInfo" @confirm="releaseChild"
			@close="releaseChildShow=false"></rf-releaseChild>
	</view>
</template>

<script>
	import {
		childList,
		addChildShare,
		receiveChildShare,
	} from '@/api/child.js'
	import {
		mapState,
	} from 'vuex';

	import {
		from
	} from 'rxjs';
	import {
		map
	} from 'rxjs/operators';


	import toast from '../../uni_modules/uview-ui/libs/config/props/toast';

	export default {
		data() {
			return {
				isReleaseButtonDisable: false, // 初始化按钮是否可用


				scrollTop: 0,
				value: '',
				// 是否全选
				isallcheck: false,
				checkboxValue1: [],
				params: {
					childSex: '',
					childAge: '',
					childName: ''
				},
				// 基本案列数据
				checkboxList1: [{
					name: '全选',
					disabled: false
				}],
				data: [],
				shareId: "", // 共管人ID
				selChild: [], //选中
				showChildJoint: false,
				// 显示共管成功或者失败
				showJoinSuc: false,
				showName: "", // 返回共享人的名字，弹出提示

				showJoinFail: false,
				showRelieveFail: false, // 解除操作
				showRelieveFail1: false,
				showRelieveFail2: false,
				showRelieveFail3: false, // 确认孩子存在共管关系

				ageList: [
					[{
						'name': '全部',
						'value': "",
					}, {
						'name': '半岁',
						'value': "0.5",
					}, {
						'name': '一岁',
						'value': "1",
					}, {
						'name': '一岁半',
						'value': "1.5",
					}, {
						'name': '两岁',
						'value': "2",
					}, {
						'name': '两岁半',
						'value': "2.5",
					}, {
						'name': '三岁',
						'value': "3",
					}, {
						'name': '三岁半',
						'value': "3.5",
					}, {
						'name': '四岁',
						'value': "4",
					}, {
						'name': '四岁半',
						'value': "4.5",
					}, {
						'name': '五岁',
						'value': "5",
					}, {
						'name': '五岁半',
						'value': "5.5",
					}, {
						'name': '六岁',
						'value': "6",
					}, {
						'name': '六岁半',
						'value': "6.5",
					}, {
						'name': '七岁',
						'value': "7",
					}]
				],
				shareChildShow: false,
				childInfo: null, // 孩子信息
				releaseChildShow: false,
				// 用于警示
				showRelieve: false,
				isSuc: true,
				title: "",
				des: "",
			};
		},

		watch: {
			// selChild(newVal) {
			// 	if (newVal.length == 1 && this.authRelease(newVal[0])) {

			// 		this.isReleaseButtonDisable = false
			// 	} else {
			// 		this.isReleaseButtonDisable = true
			// 	}
			// }
		},

		computed: {
			...mapState(['userInfo', 'hasLogin']),
			getChildAge() {
				return (val) => {

					for (let i = 0; i < this.ageList[0].length; i++) {
						if (this.ageList[0][i].value == val.childAge) {
							return this.ageList[0][i].name;
						}
					}
				}

			},
			authRelease() {
				/* 是否有解除共管权限 */
				return (val) => {

					// 存在共管，
					if (val.shareList && val.shareList.length > 0) {
						return true
						//
						// for (const element of val.shareList.filter(obj => obj.isCreate == 0)) {
						// 	if (element.teacherId == this.userInfo.id) {
						// 		return true
						// 	}
						// }
					}
					return false

				}
			},
		},
		onLoad(optios) {

			// if (optios.childList) {
			// 	this.selChild = JSON.parse(decodeURIComponent(optios.childList))
			// 	// 设置默认选中
			// 	this.getChildList()
			// } else {
			// 	this.getChildList()
			// }
		},
		onShow() {
			this.getChildList()
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		methods: {
			showToast(isSuc, title, des) {
				this.showRelieve = true;
				this.isSuc = isSuc;
				this.title = title;
				this.des = des;
			},
			OnClickedReleaseChild(child) {

				for (const element of child.shareList.filter(obj => obj.isCreate == 0)) {
					// console.log("-=-=-=-" + JSON.stringify(element));
					// console.log("-=-=-=-" + this.userInfo);
					if (element.teacherId == this.userInfo.id) {
						// 可以解除共管
						this.childInfo = child;
						this.releaseChildShow = true;
						return
					}
				}
				// 没有权限解除共管，请联系共管创建人
				this.showRelieveFail2 = true


			},
			shareChild(child) {
				// 弹出共管信息
				this.childInfo = child;
				console.log("-----------------==");
				this.shareChildShow = true;
			},
			releaseChild(list) {
				// 解除孩子共管
				console.log(JSON.stringify(list));
				console.log("releaseChild");
				this.releaseChildShow = false;
				receiveChildShare(list).then(res => {
					if (res.code == 200) {
						this.showToast(true, "解除成功", "已解除共管关系")
						this.getChildList()
					} else {
						this.showToast(false, "解除失败", "共管人正在管理孩子，请稍后重试。")
					}
				})
			},
			onBack() {
				uni.navigateBack();
			},
			OnClickedchildJoin() {
				this.showChildJoint = false;
				console.log("shareId" + this.shareId);
				// 确认共管
				var params = {
					shareId: this.shareId,
					childList: this.checkboxValue1,
				}
				console.log(JSON.stringify(params));
				addChildShare(params).then(res => {
					console.log("----", JSON.stringify(res));
					if (res.code == 200) {
						this.showName = '已将孩子共享给“' + res.data + '”您可以和他共同管理孩子'
						this.showJoinSuc = true;
						this.getChildList()
					} else {
						this.showJoinFail = true;
					}
				}).catch(err => {
					console.log("---------------", err);

					uni.showToast({
						icon: "none",
						title: err.message,
					});

				})
			},

			// 列表
			getChildList() {
				childList(this.params).then(res => {
					this.data = res.data ? res.data : []
					// 设置默认选中
					if (this.selChild.length > 0) {
						const selIds = this.selChild.map(item => item.childId)
						this.data.forEach(item => {
							item.list.forEach(content => {
								if (selIds.includes(content.childId)) {
									this.$set(content, 'isSel', true)
								}
							})

						})
					}
					console.log(this.data)
				})
			},
			checkboxChange() {
				this.isallcheck = !this.isallcheck;

				if (this.isallcheck) {
					this.checkboxValue1.length = 0
					this.selChild.length = 0

					this.data.forEach(item => {
						item.list.forEach(child => {
							this.checkboxValue1.push(child.childId);

							const arrTemp = {
								childId: child.childId,
								childName: child.childName,
								childSex: child.childSex,
								beBornDt: child.beBornDt,
								headSculpture: child.headSculpture,
							}
							this.selChild.push(arrTemp)

						});
					});
					const array = [1, 2, 2, 3, 3, 4, 5, 5];
					this.checkboxValue1 = [...new Set(this.checkboxValue1)];
				} else {
					this.checkboxValue1.length = 0
					this.selChild.length = 0
				}


				console.log("this.checkboxChange1: " + JSON.stringify(this.checkboxValue1));
			},
			// 单选，取消全选
			handleChange(val) {

				var index = this.checkboxValue1.indexOf(val.childId);
				if (index !== -1) {
					// 存在
					this.checkboxValue1.splice(index, 1);
				} else {
					// 不存在
					this.checkboxValue1.push(val.childId);
				}

				let that = this
				var isMatch = false;
				this.selChild.forEach(function(obj, index) {
					if (obj.childId === val.childId) {
						that.selChild.splice(index, 1); // 移除已选
						isMatch = true;
					}
				});

				if (!isMatch) {
					this.selChild.push(val); // 添加
				}


			},
			onClickedRelease() {
				// 解除共管
				if (this.selChild.length > 1) {
					this.showRelieveFail = true;
					return;
				}
				if (this.selChild.length < 1) {
					this.showRelieveFail1 = true;
					return;
				}
				this.childInfo = this.selChild[0];

				if (this.childInfo && this.childInfo.shareList && this.childInfo.shareList.length > 0) {

					for (const element of this.childInfo.shareList.filter(obj => obj.isCreate == 0)) {
						if (element.teacherId == this.userInfo.id) {
							// 可以解除共管
							this.releaseChildShow = true;
							return
						}
					}
					// 没有权限解除共管，请联系共管创建人
					this.showRelieveFail2 = true

				} else {
					// 请确认孩子有没有共管关系
					this.showRelieveFail3 = true
				}



			},

			onClickedJoint() {
				// 进行共管
				if (this.selChild.length < 1) {
					this.showToast(false, "请选择孩子", "创建共管可以选择多个孩子。")
					return;
				}
				this.showChildJoint = true
			},

			// 孩子详情
			childDetails(val) {
				// uni.navigateTo({
				// 	url: '/pages/childFile/childFile'
				// });
				var index = this.checkboxValue1.indexOf(val.childId);
				if (index !== -1) {
					// 存在
					this.checkboxValue1.splice(index, 1);
				} else {
					// 不存在
					this.checkboxValue1.push(val.childId);
				}

				let that = this
				var isMatch = false;
				this.selChild.forEach(function(obj, index) {
					if (obj.childId === val.childId) {
						that.selChild.splice(index, 1); // 移除已选
						isMatch = true;
					}
				});

				if (!isMatch) {
					this.selChild.push(val); // 添加
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.u-index-anchor {
		background-color: #f5f6fa !important;
	}

	.observe-content {
		min-height: calc(100vh);
		background-color: #fff;

		.observe-top {
			position: fixed;
			z-index: 999;
			width: 100%;
			height: 97px;
			background: url('../../static/icons/toubu.png');
			background-repeat: no-repeat;
			background-size: 100%;

		}

		.observe-bottom {
			position: relative;
			z-index: 990;
			top: 97px;
			background-color: #f5f7f9;

			.list-cell {
				display: flex;
				align-items: center;
				box-sizing: border-box;
				width: 100%;
				height: 148rpx;
				padding: 20px 40rpx;
				overflow: hidden;
				color: #323233;
				font-size: 14px;
				line-height: 28rpx;
				background-color: #fff;

				.cell-image {
					width: 100rpx;
					height: 100rpx;
					background-repeat: no-repeat;
					background-size: 100%;
					margin-right: 24rpx;

					.cell-icon {
						position: absolute;
						right: 0;
						bottom: 0;
					}
				}

				.cell-text {
					.cell-text-top {
						font-size: 32rpx;
						font-family: PingFangSC-Semibold, PingFang SC;
						font-weight: 600;
						color: #3a3d4b;
						margin-top: 8rpx;
					}

					.cell-text-bom {
						margin: 10rpx 0rpx;
						font-size: 24rpx;
						font-family: PingFangSC-Regular, PingFang SC;
						font-weight: 400;
						color: #77798d;
					}
				}
			}


		}

		.popup {
			width: 100%;
			height: 626rpx;
			background: #ffffff;
			border-radius: 24rpx 24rpx 0rpx 0rpx;
		}

		.footer {
			position: fixed;
			z-index: 999;
			left: 0;
			bottom: 0;
			width: 100%;
			height: 180rpx;
			background: #fff;
			box-shadow: 0rpx -4rpx 8rpx 0rpx rgba(0, 0, 0, 0.02), 0rpx -1rpx 0rpx 0rpx rgba(0, 0, 0, 0.02);


			.container {
				top: 0rpx;
				height: 112rpx;
				padding: 0rpx 32rpx;
				display: flex;
				align-items: center;


				.input {
					margin: 0rpx 0rpx 0rpx 32rpx;
					height: 88rpx;
					background-color: #F4F7F9;
					border-radius: 44rpx;
					padding: 0rpx 180rpx 0rpx 20rpx;
					flex: 2;
				}

				.btn {
					margin-left: 28rpx;
					width: 94%;
					height: 88rpx;
					border-radius: 44rpx;
					font-size: 32rpx;
					font-weight: 600;
					color: #ffffff;
					line-height: 88rpx;
					text-align: center;
					border: 1rpx solid #58c866;

					&.tColor {
						color: #58c866;
					}

					&.bg {
						background: #58c866;
					}

					&.disabled {
						background-color: #ffffff;
						color: #77798d;
						border: 2rpx solid #77798d;
					}

					// &.disabled {
					// 	background-color: #ffffff;
					// 	color: #77798d;
					// 	border: 2rpx solid #77798d;
					// }
				}


			}


		}
	}
</style>